﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using Jarvis.Server.Statistics;
using Jarvis.WCF.ServiceContracts;
using Ninject.Extensions.Logging;

namespace Jarvis.Server
{
    partial class JarvisServiceHost : ServiceBase
    {
        private ServiceHost _serviceHost;
        private readonly JarvisWcfService _singletonService;

        private readonly ILogger _logger;
        private readonly IStatisticsCollector _statisticsCollector;
        
        public JarvisServiceHost(ILoggerFactory loggerFactory, IStatisticsCollector statisticsCollector, JarvisWcfService singletonService)
        {
            InitializeComponent();

            _statisticsCollector = statisticsCollector;
            _singletonService = singletonService;
            _statisticsCollector.StartCollecting();
            _logger = loggerFactory.GetCurrentClassLogger();
        }

        protected override void OnStart(string[] args)
        {
            _logger.Trace("Service Starting");

            var baseAddresses = new Uri[]
                                    {
                                        new Uri("http://localhost:9090/Jarvis"),
                                        new Uri("net.pipe://localhost/Jarvis"),
                                    };

            _serviceHost = new ServiceHost(_singletonService, baseAddresses);

            _serviceHost.AddServiceEndpoint(typeof(ILocatorService),
            new WSDualHttpBinding(),
            "Location");

            _serviceHost.AddServiceEndpoint(typeof(ILocatorService),
              new NetNamedPipeBinding(),
              "Location");

            _serviceHost.AddServiceEndpoint(typeof(IStatisticsService),
            new WSDualHttpBinding(),
            "Stats");

            _serviceHost.AddServiceEndpoint(typeof(IStatisticsService),
              new NetNamedPipeBinding(),
              "Stats");


            var smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            _serviceHost.Description.Behaviors.Add(smb);

            _serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;

            _serviceHost.Open();

#if DEBUGSERVICE
            while (true)
            {
                Thread.Sleep(100);   
            }
#endif
        }

        protected override void OnStop()
        {
            _serviceHost.Close();
        }

#if DEBUGSERVICE
        public void DebugOnStart(string[] args){
            OnStart(args);
        }
#endif
    }
}
